package cn.itcast.order.service.impl;


import cn.itcast.feign.client.ItemClient;
import cn.itcast.feign.client.UserClient;
import cn.itcast.hmall.dto.common.ResultDTO;

import cn.itcast.hmall.dto.common.ThreadLocalUtil;
import cn.itcast.hmall.dto.order.OrderReqDTO;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.order.Order;
import cn.itcast.hmall.pojo.order.OrderDetail;
import cn.itcast.hmall.pojo.order.OrderLogistics;
import cn.itcast.hmall.pojo.user.Address;
import cn.itcast.hmall.pojo.user.User;
import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.mapper.TbOrderDetailMapper;
import cn.itcast.order.mapper.TbOrderLogisticsMapper;
import cn.itcast.order.service.OrderService;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.security.DigestException;
import java.util.Date;
import java.util.List;


@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private TbOrderDetailMapper orderDetailMapper;
    @Autowired
    private UserClient userClient;
    @Autowired
    private TbOrderLogisticsMapper orderLogisticsMapper;
    //创建订单
    @Override
    public String CreateOrder(OrderReqDTO orderReqDTO) {

        // 根据id查询商品的详细信息
        Item item = itemClient.findGoodsById(orderReqDTO.getItemId().toString());
        //得到商品价格
        Long price = item.getPrice();
        //购买的商品数量
        Integer num = orderReqDTO.getNum();
        Long totalFee= price * num;
        //创建Order对象
        Order order = new Order();
        order.setStatus(1);
        order.setTotalFee(totalFee);
        order.setPaymentType(orderReqDTO.getPaymentType());
        order.setCreateTime(new Date());
        order.setUserId(ThreadLocalUtil.getUserId());
        //把对象封装到数据库中
        orderMapper.insert(order);
        //将商品信息、orderId信息封装为OrderDetail对象，
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        orderDetail.setItemId(item.getId());
        orderDetail.setNum(num);
        orderDetail.setName(item.getName());
        orderDetail.setPrice(price);
        orderDetail.setSpec(item.getSpec());
        orderDetail.setImage(item.getImage());
        orderDetail.setCreateTime(new Date());
        //写入tb_order_detail表
        orderDetailMapper.insert(orderDetail);
        //根据addressId查询user-service服务，获取地址信息
        Address address = userClient.findAddressByIdd(orderReqDTO.getAddressId().toString());
        // 将地址封装为`OrderLogistics`对象，写入tb_order_logistics表(物流信息表)
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setContact(address.getContact());
        orderLogistics.setMobile(address.getMobile());
        orderLogistics.setProvince(address.getProvince());
        orderLogistics.setCity(address.getCity());
        orderLogistics.setTown(address.getTown());
        orderLogistics.setStreet(address.getStreet());
        orderLogistics.setCreateTime(new Date());
        orderLogisticsMapper.insert(orderLogistics);
        //修改库存
        itemClient.reductionInventory(item.getId().toString(),orderReqDTO.getNum().toString());


        return order.getId().toString();
    }

    @Override
    public Order findOrderById(String orderId) {
        return orderMapper.selectById(orderId);
    }
    //支付订单
    @Override
    public ResultDTO payOrder(String orderId, User user) {
        Order order = orderMapper.selectById(orderId);

        if (!order.getStatus().equals(1)){
            return ResultDTO.error("订单已经支付过");
        }
        User user1 = userClient.findUserById(order.getUserId().toString());
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());


        if (!password.equals(user1.getPassword())){
             return ResultDTO.error("密码错误,请重新输入");
        }

        //扣除余额并修改订单

        Boolean b = userClient.balanceOfBuckle(order.getUserId(), order.getTotalFee());
        if (!b){
            return ResultDTO.error("余额不足");
        }
        order.setStatus(2);
        orderMapper.updateById(order);

      /*  //条件更新
        LambdaUpdateWrapper<Order> wrapper = Wrappers.<Order>lambdaUpdate();
        // 更新的条件
        wrapper.eq(Order::getId,orderId)
                // 更新的值
                .set(Order::getStatus,2);*/

        return ResultDTO.ok();
    }
    //定时下架商品
    @Override
    public void timingShelves() {
        System.out.println("22222222222");
        List<Order> list1 = orderMapper.selectList(null);
        for (Order order : list1) {
            Integer status = order.getStatus();
            if (status.equals(1)) {
                long time = order.getCreateTime().getTime();
                long time1 = new Date().getTime();
                System.out.println(time1 - time);
                if ((time1 - time) > 60000) {
                    order.setStatus(5);
                    orderMapper.updateById(order);
                    //根据orderid查询商品信息
                    OrderDetail orderDetail = orderDetailMapper.selectByOrderId(order.getId());
                    //回复库存呢
                    itemClient.addInventory(orderDetail.getItemId().toString(), orderDetail.getNum().toString());
                }
            }
        }
    }
}
